<script setup lang="ts">
import type { EChartsOption, TooltipComponentFormatterCallback } from 'echarts'
import type { PieData, PieTitle } from '@/mixins/MixinElectricityRateAnalysis'
import { useChartToolboxDataView } from '@/mixins/MixinChartToolboxDataView'
import { useChartTooltipTheme } from '@/mixins/MixinChartTooltipTheme'

const props = withDefaults(
  defineProps<{
    title: PieTitle
    data: PieData[]
  }>(),
  {
    title: '饼图',
    data: () => [],
  },
)

const pieTooltipFormatter: TooltipComponentFormatterCallback<any>
= ({ color, percent, name, value, data, ...rest }) => {
  return `
    <div style="margin: 0;line-height:1;">
      <div style="font-size:14px;color:var(--el-text-color-regular);font-weight:400;line-height:1;">${rest.seriesName || name}</div>
      <div style="margin: 10px 0 0;line-height:1;">
        <div style="margin: 0;line-height:1.5;">
          <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>
          <span style="font-size:14px;color:var(--el-text-color-regular);font-weight:400;margin-left:2px">${name}：</span>
          <span style="font-size:14px;color:var(--el-text-color-regular);font-weight:900">${defaultNumber(data.value)} ${data ? data.unit || '' : ''}（${percent}%）</span>
       </div>
      </div>
    </div>
  `
}
const { dataView: chartToolboxDataView } = useChartToolboxDataView(() => ({
  optionToContent: (opt: any, g: (d: any) => string | HTMLElement) => {
    const dataset = opt.dataset[0]?.source || []
    const data = [
      ['时期', props.title.includes('消费') ? '消费量' : '成本'],
      ...dataset.map((v: any) => [v.name, v.value]),
    ]
    return g(data)
  },
}))
const tooltipTheme = useChartTooltipTheme()
const chartOption = computed<EChartsOption>(() => {
  return {
    name: props.title,
    title: {
      text: props.title,
      textStyle: {
        fontFamily: 'PingFang SC',
        fontWeight: '400',
        fontSize: 16,
      } as any,
    },
    tooltip: {
      trigger: 'item',
      formatter: pieTooltipFormatter,
      ...tooltipTheme,
    },
    legend: {
      show: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 16,
      data: props.data.map(v => `${v.name}${v.unit ? `(${v.unit})` : ''}`),
    },
    toolbox: {
      show: true,
      left: 'right',
      top: 0,
      feature: {
        dataView: unref(chartToolboxDataView),
      },
    },
  }
})
const dataset = computed(() => {
  return {
    source: props.data.map(v => ({
      name: `${v.name}${v.unit ? `(${v.unit})` : ''}`,
      value: v.value,
    })),
  }
})
</script>

<template>
  <ViewChartPie
    :option="chartOption" :dataset="dataset" :center="['50%', '45%']"
    radius="60%" :emphasis="false" :legend="false"
    style="width: 100%;height: 100%;"
  />
</template>
